<template>
  <div class="property-company-select">
    <el-select
      v-model="selectedCompanyId"
      :placeholder="placeholder"
      :disabled="disabled"
      :clearable="clearable"
      :filterable="filterable"
      :loading="loading"
      @change="handleChange"
      @clear="handleClear"
    >
      <el-option
        v-for="company in companyOptions"
        :key="company.id"
        :label="company.companyName"
        :value="company.id"
      >
        <div class="company-option">
          <div class="company-name">{{ company.companyName }}</div>
          <div class="company-code">{{ company.companyCode }}</div>
        </div>
      </el-option>
    </el-select>
  </div>
</template>

<script setup lang="ts">
/**
 * 物业公司选择组件
 * @author Wu.Liang
 * @date 2025-06-29
 * @description 提供物业公司选择功能，支持权限过滤
 */
import { ref, computed, onMounted, watch } from 'vue'
import { showMessage } from '@/utils/message'
import { useUserStore } from '@/store/user'
import { isSuperAdmin, getUserPropertyCompanyId } from '@/utils/permission'

// 物业公司信息接口
interface PropertyCompany {
  id: number
  companyName: string
  companyCode: string
  status: number
}

// Props定义
interface Props {
  /** 选中的物业公司ID */
  modelValue?: number | null
  /** 占位符文本 */
  placeholder?: string
  /** 是否禁用 */
  disabled?: boolean
  /** 是否可清空 */
  clearable?: boolean
  /** 是否可搜索 */
  filterable?: boolean
  /** 是否显示所有物业公司（超级管理员专用） */
  showAll?: boolean
  /** 是否只显示当前用户关联的物业公司 */
  onlyCurrentUser?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  placeholder: '请选择物业公司',
  disabled: false,
  clearable: true,
  filterable: true,
  showAll: false,
  onlyCurrentUser: false
})

// Emits定义
const emit = defineEmits<{
  'update:modelValue': [value: number | null]
  'change': [value: number | null, company: PropertyCompany | null]
}>()

// 用户store
const userStore = useUserStore()

// 响应式数据
const loading = ref(false)
const companyOptions = ref<PropertyCompany[]>([])
const selectedCompanyId = ref<number | null>(props.modelValue || null)

// 计算属性
const isSuperAdminUser = computed(() => isSuperAdmin())
const userPropertyCompanyId = computed(() => getUserPropertyCompanyId())

// 监听modelValue变化
watch(() => props.modelValue, (newValue) => {
  selectedCompanyId.value = newValue || null
})

// 加载物业公司列表
const loadCompanyOptions = async () => {
  try {
    loading.value = true
    
    // 这里应该调用物业公司API获取数据
    // 暂时使用模拟数据
    const mockData: PropertyCompany[] = [
      {
        id: 1,
        companyName: '智慧物业有限公司',
        companyCode: 'WY001',
        status: 1
      },
      {
        id: 2,
        companyName: '绿城物业服务集团',
        companyCode: 'WY002',
        status: 1
      },
      {
        id: 3,
        companyName: '万科物业服务有限公司',
        companyCode: 'WY003',
        status: 1
      }
    ]
    
    // 根据权限过滤数据
    let filteredData = mockData
    
    if (props.onlyCurrentUser && !isSuperAdminUser.value) {
      // 只显示当前用户关联的物业公司
      const userCompanyId = userPropertyCompanyId.value
      if (userCompanyId) {
        filteredData = mockData.filter(company => company.id === userCompanyId)
      } else {
        filteredData = []
      }
    } else if (!props.showAll && !isSuperAdminUser.value) {
      // 非超级管理员且不显示所有公司时，只显示有权限的公司
      const userCompanyId = userPropertyCompanyId.value
      if (userCompanyId) {
        filteredData = mockData.filter(company => company.id === userCompanyId)
      } else {
        filteredData = []
      }
    }
    
    companyOptions.value = filteredData
  } catch (error) {
    console.error('加载物业公司列表失败:', error)
    showMessage({ type: 'error', message: '加载物业公司列表失败' })
  } finally {
    loading.value = false
  }
}

// 处理选择变化
const handleChange = (value: number | null) => {
  emit('update:modelValue', value)
  
  const selectedCompany = companyOptions.value.find(company => company.id === value) || null
  emit('change', value, selectedCompany)
}

// 处理清空
const handleClear = () => {
  emit('update:modelValue', null)
  emit('change', null, null)
}

// 组件挂载时加载数据
onMounted(() => {
  loadCompanyOptions()
})
</script>

<style lang="scss" scoped>
.property-company-select {
  width: 100%;
  
  .company-option {
    display: flex;
    flex-direction: column;
    gap: 4px;
    
    .company-name {
      font-weight: 500;
      color: var(--el-text-color-primary);
    }
    
    .company-code {
      font-size: 12px;
      color: var(--el-text-color-secondary);
    }
  }
}
</style> 